package com.yuwei.common.mvi

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import com.yuwei.common.event.CustomEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.reflect.ParameterizedType

abstract class BaseViewFragment<VDB : ViewDataBinding> : Fragment() {


    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    val binding: VDB by lazy {
        //拿到第一个泛型的class
        val clazz = type[0] as Class<VDB>
        //通过反射,拿到activity中inflate的方法
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        //通过反射放大的调用,自定绑定第一个参数的值(布局)
        method.invoke(null, layoutInflater) as VDB
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        EventBus.getDefault().register(this)
        initView()
        initData()
    }


    abstract fun initView()
    abstract fun initData()


    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }


    /**
     * EventBus接收事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onReceiveEvent(event: CustomEvent?){
        if (event != null && event.target == this.javaClass.simpleName){
            handEvent(event)
        }
    }

    protected open fun handEvent(event: CustomEvent){

    }

}